package com.party.mobile.jms.publisher.service.impl;

import com.party.common.constant.Constant;
import com.party.core.model.system.SysConfig;
import com.party.core.model.system.SysConfigEnum;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.jms.publisher.service.IOrderCancelPubulisherService;
import org.apache.activemq.ScheduledMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yifeng
 * @createTime 2018/1/30 0030 下午 15:39
 * @description 订单取消发送者
 */
@Service
public class OrderCancelPubulisherService implements IOrderCancelPubulisherService {

    @Autowired
    private ISysConfigService sysConfigService;

    private JmsTemplate jmsOrderCancelTemplate;

    Logger logger = LoggerFactory.getLogger(getClass());

    private ExecutorService threadPool = Executors.newFixedThreadPool(5);

    public void setJmsOrderCancelTemplate(JmsTemplate jmsOrderCancelTemplate) {
        this.jmsOrderCancelTemplate = jmsOrderCancelTemplate;
    }

    public void send(final String orderId) {
        sendMessage(orderId);
    }

    public void sendMessage(final String orderId) {
        try {
            // 是否允许开启延迟队列取消订单消息
            SysConfig allowSendConfig = sysConfigService.findByCode(SysConfigEnum.ALLOW_SEND_CANCEL_ORDER.getCode());
            if (null != allowSendConfig && allowSendConfig.getValue().equals("true")) {
                // 单位是分钟
                SysConfig sendTimeConfig = sysConfigService.findByCode(SysConfigEnum.SEND_CANCEL_ORDER_TIME.getCode());
                if (sendTimeConfig != null) {
                    Integer overtime = Integer.valueOf(sendTimeConfig.getValue());
                    jmsOrderCancelTemplate.send(new MessageCreator() {
                        public Message createMessage(Session session) throws JMSException {
                            System.out.println("消息发送时间：" + System.currentTimeMillis());
                            MapMessage mapMessage = session.createMapMessage();
                            mapMessage.setString(Constant.TYPE_KEY, orderId);
                            long delayTime = overtime * 60 * 1000;
                            mapMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delayTime);
                            return mapMessage;
                        }
                    });
                }
            }
        } catch (Exception e) {
            logger.error("订单取消队列发送消息异常", e);
        }
    }
}
